﻿using System;
using System.Text;
using System.Threading;
using RabbitMQ.Client.Events;
using RabbitMQDemo.Common;

namespace RabbitMQDemo.Consumer
{
    public class Fanout
    {
        private const string ExchangeName = "fanout_exchange";

        private const string QueueNamePrefix = "fanout_queue";

        public static void Receive(string[] args)
        {
            var index = Utils.GetFirstValue(args, 1);
            var timeout = new Random().Next(1, 4);
            Console.WriteLine($"queue:{QueueNamePrefix}{index}, timeout: {timeout}s");

            using var connection = MQClient.GetConnection();
            using var channel = connection.CreateModel();

            // 声明交换机
            channel.ExchangeDeclare(exchange: ExchangeName, type: "fanout", durable: false, autoDelete: false, arguments: null);

            // 声明队列
            for (int i = 1; i < 4; i++)
            {
                var queueName = $"{QueueNamePrefix}{i}";
                channel.QueueDeclare(queue: queueName, durable: false, exclusive: false, autoDelete: false, arguments: null);
                channel.QueueBind(queue: queueName, exchange: ExchangeName, routingKey: "", arguments: null);
            }

            var consumer = new EventingBasicConsumer(channel);
            consumer.Received += (model, ea) =>
            {
                var message = Encoding.UTF8.GetString(ea.Body.ToArray());
                Console.WriteLine($"[Fanout][{ea.DeliveryTag}]received：{message}");

                Thread.Sleep(timeout * 1000);
            };

            channel.BasicConsume(queue: $"{QueueNamePrefix}{index}", autoAck: true, consumerTag: "testConsumer", noLocal: false, exclusive: false, arguments: null, consumer: consumer);

            Console.WriteLine("按任意键退出");
            Console.ReadKey();
        }
    }
}
